import com.alibaba.fastjson.{JSON, JSONObject}
import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.SQLContext
import org.elasticsearch.spark._

/**
  * @ Auther: o2o-rd-0008
  * @ Date:   2019/12/4 09:28
  * @ Param:  ${PARAM}
  * @ Description: 
  */
object modify_cate_only {

  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
    conf.setAppName(s"${this.getClass.getSimpleName}")
    conf.set("spark.debug.maxToStringFields", "500")
    conf.setMaster("local[*]")
    conf.set("es.nodes", "192.168.1.157")
    conf.set("es.port", "9200")
    conf.set("cluster.name", "O2OElastic")
    conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
    conf.set("spark.sql.caseSensitive", "true")
    val sc = new SparkContext(conf)
    val sqlContext = new SQLContext(sc)
    sc.setLogLevel("WARN")
    sc.hadoopConfiguration.set("fs.s3a.access.key", "GAO7EO9FWKPJ8WFCQDME")
    sc.hadoopConfiguration.set("fs.s3a.secret.key", "LZ0xaHBSYKHaJ9ECDbX9f7zin79UZkXfGoNapRPL")
    sc.hadoopConfiguration.set("fs.s3a.endpoint", "https://obs.cn-north-1.myhuaweicloud.com")

    val value1: RDD[String] = sc.esJsonRDD(s"2019_tmall/tmall_2019_11",
      """
        |{
        |  "query": {
        |    "term": {
        |      "good_id": {
        |        "value": "586154668317"
        |      }
        |    }
        |  }
        |}
      """
    .stripMargin).values

    val data = sqlContext.read.json(value1)

    import org.apache.spark.sql.functions._
    val frame = data.drop("firstCategoryId","secondCategoryId","thirdCategoryId","fourthCategoryId")
      .withColumn("firstCategoryId",lit("10015"))
      .withColumn("secondCategoryId",lit("1001506"))
      .withColumn("thirdCategoryId",lit("100150699"))
      .withColumn("fourthCategoryId",lit("10015069999"))

    val result = frame.toJSON.rdd.map(line => {
      val lines = JSON.parseObject(line)
      val evaluates = lines.getOrDefault("evaluates", "-1").toString
      val Base_Info = lines.getOrDefault("Base_Info", "-1").toString
      var ev = "-1"
      var str = new JSONObject
      if (evaluates.equals("-1")) {
        ev = "{\"fuyi\":\"-1\"}"
      } else {
        str = JSON.parseObject(evaluates)
      }
      if (!ev.contains("fuyi")) {
        lines.put("evaluates", str)
      } else {
        val evs = JSON.parseObject(ev)
        lines.put("evaluates", evs)
      }
      lines.put("Base_Info",Base_Info)
      lines
    })
    result.saveToEs(s"2019_tmall/tmall_2019_11", Map("es.mapping.id" -> "good_id"))
    sc.stop()
  }

}
